<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" width="800" height="600" style="box-shadow: 0 0 10px #000;"></canvas>
</body>

</html>

<script>
  var canvas = document.getElementById('canvas')
  var ctx = canvas.getContext('2d')

  var x = 0, y = 0, width = 100, height = 100;
  ctx.fillStyle = 'red'
  ctx.fillRect(x, y, width, height)

  var speedX = 2
  var speedY = 2

  function draw() {
    ctx.clearRect(0, 0, 800, 600)  // 清除画布

    // 更改坐标
    x += speedX
    y += speedY

    ctx.fillRect(x, y, width, height)

    if (x >= canvas.width - width) {
      speedX *= -1
    } else if (x <= 0) {
      speedX *= -1
    }
    if (y >= canvas.height - height) {
      speedY *= -1
    } else if (y <= 0) {
      speedY *= -1
    }

    window.requestAnimationFrame(draw)
  }

  draw()
</script>